package com.lepu.app.main.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import org.jivesoftware.smack.XMPPConnection;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;

import com.app.application.MyApplication;
import com.app.config.AppConfig;
import com.app.utils.AppEnterTongJi;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.app.utils.UpdateManager;
import com.app.utils.Utils;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.core.lib.adapter.FragmentPageAdapter;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.Reachability;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MenuBarView;
import com.core.lib.widget.MenuBarView.OnMenuBarListener;
import com.core.lib.widget.MyDialog;
import com.core.lib.widget.NoScrollViewPager;
import com.eyzhs.app.R;
import com.lepu.app.fun.chat.business.AppCommonService;
import com.lepu.app.fun.chat.business.album.AlbumHelper;
import com.lepu.app.fun.chat.business.chatcore.ClientChatXmppImpl;
import com.lepu.app.fun.chat.business.chatcore.DoctorManager;
import com.lepu.app.fun.chat.util.SingManager;
import com.lepu.app.fun.grow.fragment.FragmentGrow;
import com.lepu.app.fun.tool.jqtx.util.ToolJqtxUtil;
import com.lepu.app.fun.tool.ymsjb.util.YiMiaoUtil;
import com.lepu.app.main.fragment.MainTabFragmentCircle;
import com.lepu.app.main.fragment.MainTabFragmentGrow;
import com.lepu.app.main.fragment.MainTabFragmentHospital;
import com.lepu.app.main.fragment.MainTabFragmentIndexNew;
import com.lepu.app.main.fragment.MainTabFragmentMy;
import com.lepu.app.main.permission.PermissionUtil;
import com.lepu.app.main.push.PushUtils;
import com.lepu.app.usercenter.LoginActivity;
import com.lepu.app.usercenter.UserInfoActivity;

public class MainTabActivity extends MainActivityBase implements
		OnMenuBarListener {

	public static final int MSG_LOGIN_UPDATE = 10;// 登录成功，更 新消息
	public static final int MSG_LOGOUT_UPDATE = 11;// 注销登录,更新消息

	public static final int MSG_SHOW_LOGIN_TOKEN_DIALOG = 30;

	private static final int TAB_COUNT = 5;
	private static MainTabActivity mInstance = null;

	private NoScrollViewPager mViewPager = null;
	private MenuBarView mMenuBarView = null;

	private MyDialog mCurrentDialog;// 是否token失效的dialog

	MainTabFragmentIndexNew mFragmentIndex;
	private MainTabFragmentHospital mFragmentHospital;
	private MainTabFragmentCircle mFragmentCircle;
	private MainTabFragmentGrow mFragmentGrow;

	private boolean mRequestStartUp = false;

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@SuppressLint("ResourceAsColor")
	@Override
	public void onCreate(Bundle savedInstanceState) {

		//mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_tab_activity);

		// 初始化配置信息
		LogUtilBase.LogD(null, "MainActivity=====>>onCreate");
		mInstance = this;

		// 异常退出,恢复当前tabIndex
		int tabIndex = 0;
		if (savedInstanceState != null && savedInstanceState.size() > 0) {
			tabIndex = savedInstanceState.getInt("CurrentTabIndex");
		}
		init(tabIndex);
	}

	@Override
	protected void onStart() {

		if (mRequestStartUp) {
			mNeedDefaultBgForground = true;
		} else {
			mNeedDefaultBgForground = false;
		}
		super.onStart();

		//从后台进入前台，刷新首页
		if(mNeedDefaultBgForground)
		{
			//从后台切回前台
			bgForgroundRefresh();
		}
		mNeedDefaultBgForground = true;
		mRequestStartUp = true;
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mInstance = null;
		UpdateManager.getInstance().deleteNotification();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {

		// 异常退出，保存当前tabIndex
		outState.putInt("CurrentTabIndex", getMainMenuSelected());
		super.onSaveInstanceState(outState);
	}

	/*
	 * 在栈中被唤醒时，会进入
	 */
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		//
	}

	public static MainTabActivity getInstance() {
		return mInstance;
	}

	private void init(int tabIndex) {

		initBaiduWithApiKey();
		initGeTuiWithApiKey();

		// content
		mFragmentIndex = new MainTabFragmentIndexNew();
		mFragmentHospital = new MainTabFragmentHospital();
		mFragmentCircle = new MainTabFragmentCircle();
		mFragmentGrow = new MainTabFragmentGrow();
		MainTabFragmentMy fragmentMy = new MainTabFragmentMy();

		ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();
		fragmentList.add(mFragmentIndex);
		fragmentList.add(mFragmentHospital);
		fragmentList.add(mFragmentCircle);
		fragmentList.add(mFragmentGrow);
		fragmentList.add(fragmentMy);

		mViewPager = (NoScrollViewPager) findViewById(R.id.mainViewPager);
		mViewPager.setAdapter(new FragmentPageAdapter(
				getSupportFragmentManager(), fragmentList, null, null));
		// 是否可以滑动更新tab
		mViewPager.setNoScroll(true);
		// mViewPager.setOnPageChangeListener(new MyViewChangeListener());

		mViewPager.setOffscreenPageLimit(TAB_COUNT - 1);

		// menubar
		mMenuBarView = (MenuBarView) findViewById(R.id.mainMenuBar);
		mMenuBarView.setOnMenuBarListener(this);
		mMenuBarView.setSelectedIndex(tabIndex);

		//上传用户行为日志
		AppEnterTongJi.getInstance().requestEnterUse(this);

		// 开始加载相册服务
		AlbumHelper.getHelper();
		// chat 铃声资源
		SingManager.getInstance().preparResource();
		// // TODO: 2015/11/30
		// 开启定时刷新消息弹窗
		startChat();

		//启动程序闪屏页
		startStartAdPage();

		// 第一次使用 或升级
		AppConfig.setConfig(this, Const.CONFIG_APP_FIRST_USE, false);
		AppConfig.setConfig(this, Const.CONFIG_APP_UPGRADE_USE, false);

		PermissionUtil.checkCommonPermissions(this);

//		boolean appFirstUse = AppConfig.getConfigBoolean(this,
//				Const.CONFIG_APP_FIRST_USE, true);
//		boolean appUpgradeUse = AppConfig.getConfigBoolean(this,
//				Const.CONFIG_APP_UPGRADE_USE, true);
//		if (appFirstUse || appUpgradeUse) {
//			if (LoginUtil.checkIsLogin()) {
//				AppConfig.setConfig(this, Const.CONFIG_APP_FIRST_USE, false);
//				AppConfig.setConfig(this, Const.CONFIG_APP_UPGRADE_USE, false);
//			} else {
//				Intent intentWebGuide = new Intent(this,
//						AppEnterWebGuideActivity.class);
//				startActivityAnim(intentWebGuide, 0, 0);
//			}
//		}
	}

	/**
	 * 从后台切换回前台刷新
	 */
	private void bgForgroundRefresh()
	{
		//首页每次进来都得刷新
		if(mFragmentIndex != null)
		{
			mFragmentIndex.clearMemoryCacheDataAndRequestData();
		}
		
		//刷新医院消息
		if(mFragmentHospital != null)
		{
		    mFragmentHospital.requestNewCount();
		}
		
		int currentIndex = getMainMenuSelected();
		switch (currentIndex){
			case 0:
				//index
				mFragmentHospital.mRefreshFlag = true;
				mFragmentGrow.mRefreshFlag = true;

				break;
			case 1:
				//hospital
				mFragmentHospital.request();
				mFragmentGrow.mRefreshFlag = true;
				mFragmentCircle.mRefreshFlag = true;
				break;
			case 2:
				//mother circle
                mFragmentCircle.refreshBanner();
                mFragmentGrow.mRefreshFlag = true;
                mFragmentHospital.mRefreshFlag = true;
				break;
			case 3:
				//grow
				mFragmentGrow.refresh();
				mFragmentHospital.mRefreshFlag = true;
				mFragmentCircle.mRefreshFlag = true;
				break;
			case 4:
				mFragmentCircle.mRefreshFlag = true;
				mFragmentHospital.mRefreshFlag = true;
				mFragmentGrow.mRefreshFlag = true;
				break;
			default:
				break;
		}
	}

	private void startStartAdPage()
	{
		boolean appFirstUse = AppConfig.getConfigBoolean(this,
				Const.CONFIG_APP_FIRST_USE, true);

		String appStartAdPath = Utils.getAdFilePath(1);
		if(!TextUtils.isEmpty(appStartAdPath) && !appFirstUse)
		{
			File file = new File(appStartAdPath);
			if(file.exists())
			{
				//跳广告闪屏页
				Intent intent = new Intent(this,AppStartActivityAd.class);
				intent.putExtra("filePath",appStartAdPath);
				startActivityAnim(intent, 0, 0);
			}
		}
	}

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	public void updateStatusBar()
	{
		int index = getMainMenuSelected();
		if(index == 0)
		{
			//test
			getWindow().getDecorView().setFitsSystemWindows(false);
			UtilityBase.setStatusBarRes(this, com.lib.custom.R.drawable.app_status_bar_bg, false);
			Utils.setStatusBarTranslucent(this);
		}else{
			getWindow().getDecorView().setFitsSystemWindows(true);
			UtilityBase.setStatusBarRes(this, com.lib.custom.R.drawable.app_status_bar_bg, true);
		}
	}

	public int getMainMenuSelected() {
		return mViewPager.getCurrentItem();
	}

	public static boolean jumpLogin(BaseFragmentActivity baseFragmentActivity) {
		boolean flag = false;
		if (!MyApplication.getInstance().checkIsLogin()) {
			Intent intent = new Intent(baseFragmentActivity,
					LoginActivity.class);
			baseFragmentActivity.startActivityAnim(intent,
					R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);

			flag = true;
		}
		return flag;
	}

	public static boolean jumpUserInfo(BaseFragmentActivity baseFragmentActivity) {
		boolean flag = false;
		if (!MyApplication.getInstance().checkIsBirthday()) {
			Intent intent = new Intent(baseFragmentActivity,
					UserInfoActivity.class);
			baseFragmentActivity.startActivity(intent, true);

			UIHelper.showToast(mInstance, "请您先完善宝宝的生日信息");
			flag = true;
		}
		return flag;
	}

	/*
	 * 暂时不使用
	 */
	class MyViewChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int position, float positionOffset, int arg2) {

		}

		@Override
		public void onPageSelected(int index) {
			mMenuBarView.setSelectedIndex(index);
		}
	}

	public void setMenuTab(int index) {
		mMenuBarView.setSelectedIndex(index);
		mFragmentCircle.setTab(0);
	}

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@Override
	public void onMenuBarItemSelected(int menuIndex,View view) {
//		if (menuIndex == getMainMenuSelected())
//			return;

		mViewPager.setCurrentItem(menuIndex, false);
		//updateStatusBar();//test
		if (menuIndex == 1 && mFragmentHospital != null) {

		}

		FragmentGrow instance = FragmentGrow.getInstance();
		if (instance != null && menuIndex == 3) {
			instance.requestFirstSyncData();
		}

		if (menuIndex == 0) {
			AppEnterTongJi.clickEvent(2, "");
		} else if (menuIndex == 1) {
			AppEnterTongJi.clickEvent(22, "");
		} else if (menuIndex == 4) {
			AppEnterTongJi.clickEvent(25, "");
		}

		if(menuIndex == 0)
		{
			//index
			jumpIndexAdPage(2);
		}
		else if(menuIndex == 2)
		{
			//妈妈圈
			jumpIndexAdPage(3);
		}
	}

	/**
	 * 2:首页  3:妈妈圈
	 * @param type
	 */
	public void jumpIndexAdPage(int type){

		/**
		 * 检查今天是否显示了广告
		 */
		String dateString = DateUtilBase.stringFromDate(new Date(),DateUtilBase.YEAR_MONTH_DAY);

		Intent intent = null;
		if(type == 2)
		{
			//首页
			String filePath = Utils.getAdFilePath(2);
			if(!TextUtils.isEmpty(filePath))
			{
				File file = new File(filePath);
				if(file.exists())
				{
					String key = dateString+"_index_ad";
					String saveString = AppConfig.getConfigString(this,key,"");
					if(TextUtils.isEmpty(saveString))
					{
						AppConfig.setConfig(this,key,dateString);
						intent = new Intent(this,AppStartActivityAdIndex.class);
						intent.putExtra("type", type);
						intent.putExtra("filePath", filePath);
					}
				}
			}

		}else if(type == 3){
			//妈妈圈
			String filePath = Utils.getAdFilePath(3);
			if(!TextUtils.isEmpty(filePath)) {
				File file = new File(filePath);
				if (file.exists()) {

					String key = dateString+"_mother_circle_ad";
					String saveString = AppConfig.getConfigString(this,key,"");
					if(TextUtils.isEmpty(saveString))
					{
						AppConfig.setConfig(this,key,dateString);
						intent = new Intent(this,AppStartActivityAdIndex.class);
						intent.putExtra("type",type);
						intent.putExtra("filePath", filePath);
					}
				}
			}
		}

		if(intent != null)
		{
			startActivityAnim(intent,
					0, 0);
		}
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			FragmentGrow fragmentGrow = FragmentGrow.getInstance();
			MainTabFragmentMy tabMyFragment = MainTabFragmentMy.getInstance();

			switch (msg.what) {
			case MSG_LOGIN_UPDATE:
			case MSG_LOGOUT_UPDATE:
				if (msg.what == MSG_LOGIN_UPDATE) {
					if (fragmentGrow != null) {
						fragmentGrow.updateAlbumCover();
						fragmentGrow.updateData(false);

						fragmentGrow.mFirstSyncData = true;
					}

					if (tabMyFragment != null) {
						tabMyFragment.updateLoginState();
					}
					// 开启聊天
					startChat();
					// 更新doctor 表
					DoctorManager.getInstance().updateDoctorID();
					ObserverManager.getInstance().notify(
							ObserverConst.NOTIFY_MOTHER_CIRCLE_CHANGE, null,
							null);

					// 下载经期提醒数据
					ToolJqtxUtil.getInstance(mInstance).requestJqtxData();
					
					// 下载疫苗提醒数据
					YiMiaoUtil.getInstance(mInstance).requestData();

				} else if (msg.what == MSG_LOGOUT_UPDATE) {

					if (fragmentGrow != null) {
						fragmentGrow.updateAlbumCover();
						fragmentGrow.clearDataList();
						fragmentGrow.updateLoginInfo();
					}

					if (tabMyFragment != null) {
						tabMyFragment.updateLoginState();
					}

					ObserverManager.getInstance().notify(ObserverConst.NOTIFY_MOTHER_CIRCLE_CHANGE, null,null);
					
					YiMiaoUtil.getInstance(mInstance).cleanData();

					LoginUtil.clearUserIcon(mInstance);
				}
				break;
			case MSG_SHOW_LOGIN_TOKEN_DIALOG:
				showDialogTokenLogin("");
			default:
				break;
			}
		}

		;
	};

	/*
	 * 通过lib_core的网络请求，反射调入这个方法
	 */
	public void showDialogTokenLogin(String status) {

		LoginUtil.loginOut();
		MainTabActivity.getInstance().mHandler
				.sendEmptyMessage(MainTabActivity.MSG_LOGOUT_UPDATE);

		AppManager.getAppManager().finishAllActivityNoClass(
				MainTabActivity.class);

		if (mCurrentDialog != null && mCurrentDialog.isShowing()) {
			mCurrentDialog.dismiss();
		}
		mCurrentDialog = null;

		if (mCurrentDialog == null) {
			int msgId = R.string.login_token_error_dialog_message;
			if (!TextUtils.isEmpty(status) && status.equals("108")) {
				msgId = R.string.login_token_error_dialog_message2;
			}
			mCurrentDialog = new MyDialog(this)
					.setMessage(msgId)
					.setNegativeButton(R.string.app_cancel,
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {

								}
							})
					.setPositiveButton(R.string.app_ok,
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									MainTabActivity.jumpLogin(MainTabActivity
											.getInstance());

								}
							});
			mCurrentDialog.create(null);
			mCurrentDialog.setCancelable(false);
			mCurrentDialog.setCanceledOnTouchOutside(false);
			mCurrentDialog.showMyDialog();
		}
	}

	/**
	 * 登录openfire
	 */
	public void startChat() {

//		if (Reachability.checkNetwork(this)
//				&& ClientChatXmppImpl.getInstance().isConnectionClosed()) {
//			try {
//				XMPPConnection connection = ClientChatXmppImpl.getInstance()
//						.getConnection();
//				if (connection != null && connection.isConnected()) {
//					LogUtilBase.LogD("xmpp", "exit success ");
//					AppCommonService.getInstance().logoutXGXMPP();
//					return;
//				}
//				if (LoginUtil.checkIsLogin()
//						&& (connection == null || !connection.isConnected())) {
//					AppCommonService.getInstance().setupChatService();
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
	}

	// 以apikey的方式绑定
	private void initBaiduWithApiKey() {
		// Push: 无账号初始化，用api key绑定
		/*
		 * PushManager.startWork(getApplicationContext(),
		 * PushConstants.LOGIN_TYPE_API_KEY, UtilityBase.getAppMetedata(this,
		 * "api_key"));
		 */

		PushManager.startWork(getApplicationContext(),

				PushConstants.LOGIN_TYPE_API_KEY,
				PushUtils.getMetaValue(mInstance, "api_key"));
		//PushManager.stopWork(this);//停止推送

	}

	// 以apikey的方式绑定
	private void initGeTuiWithApiKey() {

		// SDK初始化，第三方程序启动时，都要进行SDK初始化工作
		com.igexin.sdk.PushManager.getInstance().initialize(this.getApplicationContext());

	}
}
